const log4js = require('../utils/log4js');
const configure = require('little-man-config');

const appCfg = configure.get('app');
const blankList = configure.get('blankList');

module.exports = (req, res, next) => {
    if (appCfg.debug || blankList.freedom.includes(req.route.path)) {
        next();
    } else {
        let token = req.headers['authorization'] || req.headers['Authorization'] || req.query.token || req.body.token || '';

        let _rdm = token.split('|')[0] || '';
        let _sign = token.split('|')[1] || '';

        // console.log('_rdm',token, _rdm, _sign, JSON.stringify(req.headers));

        if (!_rdm || !_sign) {
            res.jsonWrap(null, -996, '非法请求');
        } else {
            if (_sign !== helper.md5(_rdm + 'ytmd@2018-wjchang')) {
                res.jsonWrap(null, -995, '签名错误');
            } else {
                db().sign_ddos_check.count({where: {_sign: _sign}}).then(count => {
                    if (count) {
                        res.jsonWrap(null, -994, '签名已失效');
                    } else {

                        db().sign_ddos_check.create({id: helper.uuid(), _sign: _sign, count: 1}).then().catch(e => {
                            log4js.error(e);
                            res.jsonWrap(null, 1, e.message);
                        });

                        next();
                    }
                }).catch(e => {
                    log4js.error(e);
                    res.jsonWrap(null, 1, e.message);
                });
            }
        }
    }
};